package com.heima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.heima.mapper.UserMapper;
import com.heima.pojo.dto.LoginDto;
import com.heima.pojo.entity.User;
import com.heima.pojo.vo.LoginUserVo;
import com.heima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl  implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public LoginUserVo login(LoginDto dto) {

        //参数校验
        if (dto == null || dto.getLoginName() == null || dto.getPassword() == null) {
            return LoginUserVo.fail("用户名或密码不能为空");
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();//创建条件构造器
        wrapper.eq(User::getLoginName,dto.getLoginName());//添加查询条件
        User user = userMapper.selectOne(wrapper);

        if(user == null){ //代表用户不存在得
            return LoginUserVo.fail("用户不存在");
        }
        if(!user.getPassword().equals(dto.getPassword())){ //代表密码错误
//            return LoginUserVo.fail("密码错误");
        }
        //密码相等
        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setUserId(user.getId());//设置用户id
        loginUserVo.setUserName(user.getUserName());//设置用户名
        loginUserVo.setRoleCode(user.getRoleCode());//设置角色
        loginUserVo.setSuccess(true);//设置成功
        loginUserVo.setMsg("登录成功");//设置信息
        loginUserVo.setToken(UUID.randomUUID().toString());//设置token
        return loginUserVo;
    }

    /**
     * 获取图片验证码
     * @param clientToken
     * @return
     */

    @Override
    public void imgToken(String clientToken, HttpServletResponse response) throws IOException {
        // 1. 生成随机验证码文本（如 4位字母数字）
        String code = generateCaptchaText(4);

        // 2. 将验证码存入 Redis，key = "captcha:" + clientToken
        stringRedisTemplate.opsForValue().set(
                "captcha:" + clientToken,
                code,
                300, TimeUnit.SECONDS // 5分钟过期
        );

        // 3. 创建验证码图片
        BufferedImage image = createCaptchaImage(code);

        // 4. 设置响应头
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        // 5. 写出图片到响应流
        ImageIO.write(image, "jpeg", response.getOutputStream());
    }

    // 生成随机验证码文本
    private String generateCaptchaText(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

    // 创建验证码图片
    private BufferedImage createCaptchaImage(String text) {
        int width = 100;
        int height = 40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 边框
        g.setColor(Color.GRAY);
        g.drawRect(0, 0, width - 1, height - 1);

        // 字体
        g.setFont(new Font("Arial", Font.BOLD, 22));
        g.setColor(Color.BLACK);

        // 绘制字符（带轻微偏移，增加识别难度）
        int x = 15;
        Random random = new Random();
        for (char c : text.toCharArray()) {
            int y = 25 + random.nextInt(5) - 2;
            g.drawString(String.valueOf(c), x, y);
            x += 20;
        }

        // 干扰线
        g.setColor(Color.LIGHT_GRAY);
        for (int i = 0; i < 8; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        g.dispose();
        return image;
    }
}
